/**
 * @copyright chuzhixin 1204505056@qq.com
 * @description 格式化时间
 * @param time
 * @param cFormat
 * @returns {string|null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null;
  }
  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string" && /^[0-9]+$/.test(time)) {
      time = parseInt(time);
    }
    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    if (result.length > 0 && value < 10) {
      value = "0" + value;
    }
    return value || 0;
  });
  return time_str;
}

/**
 * @copyright chuzhixin 1204505056@qq.com
 * @description 格式化时间
 * @param time
 * @param option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (("" + time).length === 10) {
    time = parseInt(time) * 1000;
  } else {
    time = +time;
  }
  const d = new Date(time);
  const now = Date.now();

  const diff = (now - d) / 1000;

  if (diff < 30) {
    return "刚刚";
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + "分钟前";
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + "小时前";
  } else if (diff < 3600 * 24 * 2) {
    return "1天前";
  }
  if (option) {
    return parseTime(time, option);
  } else {
    return (
      d.getMonth() +
      1 +
      "月" +
      d.getDate() +
      "日" +
      d.getHours() +
      "时" +
      d.getMinutes() +
      "分"
    );
  }
}

/**
 * @copyright chuzhixin 1204505056@qq.com
 * @description 将url请求参数转为json格式
 * @param url
 * @returns {{}|any}
 */
export function paramObj(url) {
  const search = url.split("?")[1];
  if (!search) {
    return {};
  }
  return JSON.parse(
    '{"' +
    decodeURIComponent(search)
    .replace(/"/g, '\\"')
    .replace(/&/g, '","')
    .replace(/=/g, '":"')
    .replace(/\+/g, " ") +
    '"}'
  );
}

/**
 * @copyright chuzhixin 1204505056@qq.com
 * @description 父子关系的数组转换成树形结构数据
 * @param data
 * @returns {*}
 */
export function translateDataToTree(data) {
  const parent = data.filter(
    (value) => value.parentId === "undefined" || value.parentId == null
  );
  const children = data.filter(
    (value) => value.parentId !== "undefined" && value.parentId != null
  );
  const translator = (parent, children) => {
    parent.forEach((parent) => {
      children.forEach((current, index) => {
        if (current.parentId === parent.id) {
          const temp = JSON.parse(JSON.stringify(children));
          temp.splice(index, 1);
          translator([current], temp);
          typeof parent.children !== "undefined" ?
            parent.children.push(current) :
            (parent.children = [current]);
        }
      });
    });
  };
  translator(parent, children);
  return parent;
}

/**
 * @copyright chuzhixin 1204505056@qq.com
 * @description 树形结构数据转换成父子关系的数组
 * @param data
 * @returns {[]}
 */
export function translateTreeToData(data) {
  const result = [];
  data.forEach((item) => {
    const loop = (data) => {
      result.push({
        id: data.id,
        name: data.name,
        parentId: data.parentId,
      });
      const child = data.children;
      if (child) {
        for (let i = 0; i < child.length; i++) {
          loop(child[i]);
        }
      }
    };
    loop(item);
  });
  return result;
}

/**
 * @copyright chuzhixin 1204505056@qq.com
 * @description 10位时间戳转换
 * @param time
 * @returns {string}
 */
export function tenBitTimestamp(time) {
  const date = new Date(time * 1000);
  const y = date.getFullYear();
  let m = date.getMonth() + 1;
  m = m < 10 ? "" + m : m;
  let d = date.getDate();
  d = d < 10 ? "" + d : d;
  let h = date.getHours();
  h = h < 10 ? "0" + h : h;
  let minute = date.getMinutes();
  let second = date.getSeconds();
  minute = minute < 10 ? "0" + minute : minute;
  second = second < 10 ? "0" + second : second;
  return y + "年" + m + "月" + d + "日 " + h + ":" + minute + ":" + second; //组合
}

/**
 * @copyright chuzhixin 1204505056@qq.com
 * @description 13位时间戳转换
 * @param time
 * @returns {string}
 */
export function thirteenBitTimestamp(time) {
  const date = new Date(time / 1);
  const y = date.getFullYear();
  let m = date.getMonth() + 1;
  m = m < 10 ? "" + m : m;
  let d = date.getDate();
  d = d < 10 ? "" + d : d;
  let h = date.getHours();
  h = h < 10 ? "0" + h : h;
  let minute = date.getMinutes();
  let second = date.getSeconds();
  minute = minute < 10 ? "0" + minute : minute;
  second = second < 10 ? "0" + second : second;
  return y + "年" + m + "月" + d + "日 " + h + ":" + minute + ":" + second; //组合
}

/**
 * @copyright chuzhixin 1204505056@qq.com
 * @description 获取随机id
 * @param length
 * @returns {string}
 */
export function uuid(length = 32) {
  const num = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
  let str = "";
  for (let i = 0; i < length; i++) {
    str += num.charAt(Math.floor(Math.random() * num.length));
  }
  return str;
}

/**
 * @copyright chuzhixin 1204505056@qq.com
 * @description m到n的随机数
 * @param m
 * @param n
 * @returns {number}
 */
export function random(m, n) {
  return Math.floor(Math.random() * (m - n) + n);
}

/**
 * @copyright chuzhixin 1204505056@qq.com
 * @description addEventListener
 * @type {function(...[*]=)}
 */
export const on = (function() {
  return function(element, event, handler, useCapture = false) {
    if (element && event && handler) {
      element.addEventListener(event, handler, useCapture);
    }
  };
})();

/**
 * @copyright chuzhixin 1204505056@qq.com
 * @description removeEventListener
 * @type {function(...[*]=)}
 */
export const off = (function() {
  return function(element, event, handler, useCapture = false) {
    if (element && event) {
      element.removeEventListener(event, handler, useCapture);
    }
  };
})();



/**
 * @copyright liuzhenhao
 * @description 根据身份证号获取 出生年月 年龄 性别
 * @param cardNum
 * @returns {object}
 */
export function getCarddetail(cardNum) {
  if (cardNum.length != 20 && cardNum.length != 18) {
    return null
  }
  // if (cardNum.length == 20) {
  //   cardNum = cardNum.substring(0, 18)
  // }
  let obj = {};
  //获取出生日期
  obj.birthday = cardNum.substring(6, 10) + "-" + cardNum.substring(10, 12) + "-" + cardNum.substring(12, 14);
  // 获取性别
  if (parseInt(cardNum.substr(16, 1)) % 2 == 1) {
    obj.sex = 1;
  } else {
    obj.sex = 2;
  }
  //获取年龄
  const myDate = new Date();
  const month = myDate.getMonth() + 1;
  const day = myDate.getDate();
  let age = myDate.getFullYear() - cardNum.substring(6, 10) - 1;
  if (cardNum.substring(10, 12) < month || (cardNum.substring(10, 12) == month && cardNum.substring(12, 14) <= day)) {
    age++;
  }
  obj.age = age;
  return obj;
}
/**
 * @copyright liuzhenhao
 * @description 根据出生年月获取年龄
 * @param value
 * @returns {number}
 */
export function getBirthdayage(value) {
  //获取年龄
  const myDate = new Date();
  const month = myDate.getMonth() + 1;
  const day = myDate.getDate();
  let age = myDate.getFullYear() - value.substring(0,4) - 1;
  if (value.substring(5, 7) < month || (value.substring(5, 7) == month && value.substring(8, 10) <= day)) {
    age++;
  }
  return age;
}


export function generateMixed(n) {
  const chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
  let res = "";
  for(let i = 0; i < n ; i ++) {
      let id = Math.ceil(Math.random()*35);
      res += chars[id];
  }
  res = res + "" + new Date().getTime()
  return res;
}


/**
 * 将unix时间戳转换为指定格式
 * @param unix   时间戳【秒】
 * @param format 转换格式
 * @returns {*|string}
 */
export function unixToDate (unix, format) {
  if (!unix) return unix
  let _format = format || 'yyyy-MM-dd hh:mm:ss'
  const d = new Date(unix * 1000)
  const o = {
    'M+': d.getMonth() + 1,
    'd+': d.getDate(),
    'h+': d.getHours(),
    'm+': d.getMinutes(),
    's+': d.getSeconds(),
    'q+': Math.floor((d.getMonth() + 3) / 3),
    S: d.getMilliseconds()
  }
  if (/(y+)/.test(_format)) _format = _format.replace(RegExp.$1, (d.getFullYear() + '').substr(4 - RegExp.$1.length))
  for (const k in o) if (new RegExp('(' + k + ')').test(_format)) _format = _format.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
  return _format
}


 export function sex (cellValue) {
  if (cellValue == '1') {
    return '男'
  } else if (cellValue == '2') {
    return '女'
  } else {
    return ''
  }
}


/**
 * @description 年龄格式化
 * @param {String} age0
 */
export function age (birthday,isage) {
  if (!birthday || birthday === '0' || Number(birthday) < 0) {
    return ''
  }
    var returnAge;
    var strBirthdayArr= birthday.split("-");
    var birthYear = strBirthdayArr[0];
    var birthMonth = strBirthdayArr[1];
    var birthDay = strBirthdayArr[2];
    const d = new Date();
    var nowYear = d.getFullYear();
    var nowMonth = d.getMonth() + 1;
    var nowDay = d.getDate();
    if(nowYear == birthYear){
      returnAge = 0;//同年 则为0岁
    } else{
      var ageDiff = nowYear - birthYear ; //年之差
      if(ageDiff > 0){
        if(nowMonth == birthMonth) {
          var dayDiff = nowDay - birthDay;//日之差
          if(dayDiff < 0){
            returnAge = ageDiff - 1;
          }else{
            returnAge = ageDiff ;
          }
        }else{
          var monthDiff = nowMonth - birthMonth;//月之差
          if(monthDiff < 0){
            returnAge = ageDiff - 1;
          }else{
            returnAge = ageDiff ;
          }
        }
      } else{
        returnAge = -1;//出生日期不能大于今天
      }
    }
    if(isage){
      return returnAge
    }
    return returnAge + '岁';
}



/**
 * 计算传秒数的倒计时【天、时、分、秒】
 * @param diftime
 */
 export function countTimeDown (diftime) {
  const leftTime = (time) => {
    if (time < 10) time = '0' + time
    return time + ''
  }
  const day = leftTime(parseInt(diftime / 60 / 60 / 24, 10))
  const hours = leftTime(parseInt(diftime / 60 / 60 % 24, 10))
  const minutes = leftTime(parseInt(diftime / 60 % 60, 10))
  const second = leftTime(parseInt(diftime % 60, 10))
  if (day > 0) {
    return day + '天' + hours + '小时' + minutes + '分钟' + second + '秒'
  }
  if (day <= 0) {
    if (hours === '00') {
      if (minutes === '00') {
        if (second === '00') {
          return '0'
        } else {
          return second + '秒'
        }
      } else {
        if (second === '00') {
          return minutes + '分钟'
        } else {
          return minutes + '分钟' + second + '秒'
        }
      }
    } else {
      return hours + '小时' + minutes + '分钟' + second + '秒'
    }
  }
}



/**
 * @description 老人来源
 * @param {String} source_type 1 -- 政府指派  2 --- 拓展客户
 */
 export function sourceType (cellValue) {
  if (cellValue === '1') {
    return '政府指派'
  } else if (cellValue === '2') {
    return '拓展客户'
  } else {
    return '暂无'
  }
}


/**
 * @description 收费类型
 * @param {String}
 */
export function payType (cellValue) {
  if (cellValue === '1') {
    return '免费'
  } else if (cellValue === '2') {
    return '次数收费'
  } else if (cellValue === '3') {
    return '小时收费'
  } else {
    return '暂无'
  }
}


export function elderlyCategory (cellValue) {
  const elderlyCategory = {
    1: '自理型',
    2: '介护型',
    3: '介助型',
    4: '全护型'
  }
  if (!elderlyCategory[cellValue]) {
    return '无'
  }
  return elderlyCategory[cellValue]
}

/**
 * @description 人脸识别未通过原因
 * @param {String}
 */
export function faceFailed (cellValue) {
  const faceFailed = {
    0: '无',
    '-2': '限制人员',
    '-3': '人员过期',
    '-4': '不在调度时间',
    '-5': '节假日',
    '-6': '温度过高',
    '-7': '未带口罩',
    '-8': '未带安全帽',
    '-9': '卡号未注册',
    '-10': '人证不匹配',
    '-11': '未授权'
  }
  if (!cellValue) {
    return ''
  }
  return faceFailed[cellValue]
}
